﻿using Corina.DataContext.Master;
using Corina.Datamodel.DataObject;
using Corina.Utilities;
using FineUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Corina.Web.IMS
{
    public partial class Login : PageviewBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                InitCaptchaCode();
            }
        }

        /// <summary>
        /// 初始化验证码
        /// </summary>
        private void InitCaptchaCode()
        {
            // 创建一个 6 位的随机数并保存在 Session 对象中
            Session["CaptchaImageText"] = GenerateRandomCode();
            imgCaptcha.ImageUrl = "~/captcha/captcha.ashx?w=150&h=30&t=" + DateTime.Now.Ticks;
        }

        /// <summary>
        /// 创建一个 6 位的随机数
        /// </summary>
        /// <returns></returns>
        private string GenerateRandomCode()
        {
            string s = String.Empty;
            Random random = new Random();
            for (int i = 0; i < 6; i++)
            {
                s += random.Next(10).ToString();
            }
            return s;
        }

        protected void button_login_Click(object sender, EventArgs e)
        {
            if (tbxCaptcha.Text != Session["CaptchaImageText"].ToString())
            {
                Alert.ShowInTop("验证码错误！");
                return;
            }
            else
            {
                ResultInfo result = GetInstance<UserMaster>().Login(tbxUserName.Text, SecurityHelper.GetMd5(tbxPassword.Text));
                if(result.Result == Enumerations.ResultValue.Succeed)
                {
                    PageContext.Redirect("/");
                }
                else
                {
                    Alert.Show(result.Result.ToString(), "登录提示");
                }
            }
        }

        protected void button_refresh_Click(object sender, EventArgs e)
        {
            InitCaptchaCode();
        }
    }
}